/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.bootstrap;

import org.openislands.oi.console.config.Actuator;
import org.openislands.oi.console.config.LineReaderConfig;
import org.openislands.oi.console.config.OIConsole;
import org.openislands.oi.console.config.ServiceManager;
import org.openislands.oi.console.config.bean.BeanContainer;
import org.openislands.oi.console.exception.CommandException;
import org.openislands.oi.console.exception.ExitException;
import org.springframework.context.annotation.ComponentScan;

import java.io.IOException;
import java.util.Arrays;

@ComponentScan(basePackages = {
        "org.openislands.oi.console",
        "org.openislands.oi.rpc.http",
})
public class Console {

    public static void main(String[] args) {
        if (args.length > 0) {
            try {
                OIConsole.load();
                ServiceManager.loadConfig();
            } catch (IOException e) {
                OIConsole.console(e.getMessage());
                return;
            }
            if ("-console".equals(args[0])) {
                console(args);
            } else {
                cli(args);
            }
        } else {
            System.out.println("Use -console enter console. -help/-h get help.");
        }
    }

    public static void console(String[] args) {
        LineReaderConfig.welcome();
        BeanContainer.initContainer(Console.class);
        Actuator.start();
    }

    public static void cli(String[] args) {
        BeanContainer.initContainer(Console.class);
        try {
            Actuator.actuatorInit();
            Actuator.CommandParser.parse(Arrays.asList(args)).execute();
        } catch (CommandException e) {
            LineReaderConfig.tips();
        } catch (ExitException ignored) {
        } catch (Exception e) {
            OIConsole.console("execute error : " + e.getMessage());
        }
    }
}
